<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-03 11:15:37
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;

use App\Http\Services\Service;
use App\Models\Company;
use App\Models\FinanceReceiving;
use App\Repositories\MarketComplaintRepository;
use App\Repositories\MarketOrderRepository;
use App\Repositories\MarketRetailRepository;
use App\Repositories\MarketRetailDetailsRepository;
use App\Repositories\MarketOfferPromotionsRepository;
use App\Repositories\MarketOfferRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property MarketRetailRepository $repository
 * @property MarketRetailDetailsRepository $details
 * @property Company $company
 * @property MarketOrderRepository $order
 * @property MarketOfferPromotionsRepository      $promotion
 * @property MarketOfferRepository      $offer
 */
class RetailService extends Service
    {
    public $details;

    public function boot(
        MarketRetailRepository $repository,
        MarketRetailDetailsRepository $details,
        Company $company,
        MarketOrderRepository $order,
        MarketOfferRepository $offer,
        MarketOfferPromotionsRepository $promotion
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        $this->company    = $company;
        $this->order      = $order;
        $this->offer      = $offer;
        $this->promotion  = $promotion;
        }

    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function details()
        {
        $data = $this->details->condition(request())->getGrid();
        return $data;
        }
    private function saveCarry($model)
        {
        $model->details->filter(function ($row) use ($model)
            {
            if ($model->carry_id == $row->carry_id)
                return;
            else if ($row->carry_id > 0)
                $row->removeCarryItem();

            if ($model->carry_id > 0)
                $row->addCarryItem($model->carry_id, $row->main->code);

            });
        }
    private function saveCar($model)
        {

        $model->details->filter(function ($row) use ($model)
            {
            if ($model->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();
            if ($model->car_id > 0)
                $row->addCarItem($model->creator->department?->name ?? "染厂", $model->customer->name, $model->car_id);
            });
        }
    protected function uploadAttachment()
        {
        $data  = request()->toArray();
        $Order = $this->repository->whereId($data['id'])->first();
        if ($Order->status_id == 2) {
            fail("财务已审核！无法修改");
            }
        $gdata = $this->repository->autosave(['id' => $data['id'], 'attachments' => $data['attachments']]);
        $gdata->details->filter(function ($v) use ($gdata)
            {
            $v->attachment = $gdata->attachment;
            $v->save();
            });
        }
    protected function save()
        {
        $data = request()->toArray();

        $id = is_numeric($data['id'] ?? "") ? $data['id'] : 0;
        if ($id !== 0) {
            $gdata = $this->repository->whereId($id)->getOne();
            if ($gdata->status_id != '0') {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            }
        if (count($data['details'] ?? []) == 0) {
            fail("订单状态明细不能为空！");
            }
        //需要重新出库的
        $needReOutStorage = [];
        //不需要出库的
        $notNeedOutStorage = [];
        //合计订单包/重
        $se_quantity                = $quantity = $auxiliary_quantity = $amount = $se_amount = $red_quantity = 0;
        $data['details']            = array_map(function ($v) use ($data, &$quantity, &$se_quantity, &$auxiliary_quantity, &$amount, &$red_quantity, &$se_amount, &$notNeedOutStorage, &$needReOutStorage)
            {
            if (isset($v['id']) && is_numeric($v['id']) && $v['id'] > 0) {
                $item = $this->details->whereId($v['id'])->first();
                //数量不一致，需要重新出库！
                if ($item['quantity'] != $v['quantity']) {
                    $needReOutStorage[] = $v['id'];
                    }
                else {
                    $notNeedOutStorage[] = $v['id'];
                    }
                }
            $quantity += $v['quantity'];
            $se_quantity += $v['se_quantity'];
            $amount += $v['amount'];
            $v['red_quantity']     = $v['quantity'];
            $red_quantity += $v['red_quantity'];
            $auxiliary_quantity += $v['auxiliary_quantity'];
            $v['se_amount']        = $v['amount'];
            $se_amount += $v['se_amount'];
            $v['md_quantity']      = $v['se_quantity'];
            $v['se_price']         = $v['price'];
            $v['main_customer_id'] = $data['customer_id'];

            return $v;
            }, $data['details']);
        $data['se_amount']          = $se_amount;
        $data['se_quantity']        = $se_quantity;
        $data['quantity']           = $quantity;
        $data['red_quantity']       = $red_quantity; //可退货数量
        $data['auxiliary_quantity'] = $auxiliary_quantity;
        $data['amount']             = $amount;
        $gdata['department_id']     = auth()->user()->department_id;
        $gdata                      = $this->repository->autosave($data);

        $this->saveCar($gdata);
        $this->saveCarry($gdata);
        $gdata->details->filter(function ($v) use ($gdata, $needReOutStorage, $notNeedOutStorage)
            {

            if ($v->iscustomer == 0) {
                //匹配报价
                $v->offer_code = $this->offer->mate($v->material_id, $v->type_id)?->code;
                //匹配优惠卷
                $promotion = $this->promotion->mate(
                    1,
                    $v->grade,
                    $v->material_id,
                    $v->color,
                    $v->customer,
                    $v->quantity
                );
                if ($promotion->count() > 0) {
                    $v->promotion_code = $promotion->first()->code;
                    }
                }
            $v->code          = $gdata->code;
            $v->singler_id    = $gdata->singler_id;
            $v->department_id = $gdata->department_id;
            $v->billdate      = $gdata->billdate;
            $v->tax_id        = $gdata->tax_id;
            $v->attachment    = $gdata->attachment;
            if (in_array($v->id, $needReOutStorage)) {
                //取消出库 取消占用
                $v->nosubStorage()->nouseStorage();
                }
            if (!in_array($v->id, $notNeedOutStorage)) {
                $v->useStorage('零售发货', $gdata->code)->subStorage();
                }
            //订单发货，更新交货数量
            $v->iscustomer == 1 && $this->order->delivery($v->order_detail_id, $v->quantity);

            $v->save();
            });
        //保存收款单！
        $this->repository->saveCollection($data['collection'], $gdata);

        return true;
        }
    protected function audit()
        {
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id != 0) {
                fail("但是非未审核状态！，无法审核！");
                }
            $Order->billdate = date("Y-m-d");
            $Order->details->filter(function ($v)
                {
                $v->billdate = date("Y-m-d");
                auditSave($v);
                });
            auditSave($Order);
            });
        }
    protected function fauditmain()
        {
        $financeremark = request("financeremark") ?? "";
        $query         = $this->repository->whereIn("id", $this->getRequestIds());
        if (isEmpty($financeremark)) {
            return $query->finance();
            }
        else
            return $query->get()->filter(function ($order) use ($financeremark)
                {
                if ($order->status_id != 1) {
                    fail("订单状态【{$order->status->name}】,无法财审！");
                    }
                $order->financeremark = $financeremark;
                $order->finance();
                });
        }
    protected function faudit()
        {
        $list    = $this->details->whereIn("id", $this->getRequestIds())->get();
        $red_ids = $list->pluck("main_id");
        $codes   = $list->pluck("code");
        // DB::enableQueryLog();
        $this->repository->whereIn("code", $codes)->finance();
        // dd(DB::getQueryLog());1
        MarketComplaintRepository::whereIn("id", $red_ids)->finance();
        }
    protected function nofaudit()
        {
        $list    = $this->details->whereIn("id", $this->getRequestIds())->get();
        $red_ids = $list->pluck("main_id");
        $codes   = $list->pluck("code");
        $this->repository->whereIn("code", $codes)->nofinance();

        MarketComplaintRepository::whereIn("id", $red_ids)->nofinance();
        }
    /**
     * Summary of noaudit
     * @return mixed
     */
    protected function noaudit()
        {
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id == 2) {
                fail("财务已审核！无法修改");
                }
            if ($Order->status_id != 1) {
                fail("非审核状态！，无法反审！");
                }
            $Order->details->filter(function ($v)
                {
                if ($v->red->count() > 0) {
                    fail("{$v['code']}做了客诉！，无法反审！");
                    }
                auditSave($v, false);
                });
            auditSave($Order, false);
            });
        }

    public function getDetail()
        {
        return $this->details->whereIn("id", $this->getRequestIds())->getList();
        }
    public function getOrder()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->getList();
        }
    protected function delete()
        {

        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id == 1)
                fail("单据已审核！");
            if ($v->status_id == 2)
                fail("单据已财审！");
            //删除明细
            $v->details->filter(function ($detail)
                {
                //取消出库
                $detail->nosubStorage()->nouseStorage()->delete();
                //订单发货，更新交货数量
                $detail->iscustomer == 1 && $this->order->delivery($detail->order_detail_id, 0 - $detail->quantity);
                });

            // 删除收款
            $finance = FinanceReceiving::whereOrder_code($v->code)->first();
            if ($finance) {
                if ($finance->status_id == 1) {
                    fail("收款单[{$v['code']}]已审核！禁止删除！");
                    }
                $finance->delete();
                }
            $v->delete();
            });
        }

    public function printReport()
        {
        $market = $this->repository->whereIn("id", $this->getRequestIds())->first();

        $data = $this->details->where("code", $market?->code)->setRelation(['order'])->getList();
        // dd($data);
        return createReport($data->toArray());
        }
    }